
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.w3c.dom.Document;

import com.facebook.api.Facebook;
import com.facebook.api.FacebookException;
import com.facebook.api.FacebookRestClient;

/**
 * Servlet implementation class for Servlet: HistoriqueServlet
 *
 */
 public class HistoriqueServlet extends FacebookServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
   private FacebookRestClient fbrclient;
   private Database db;
   
   public HistoriqueServlet() {
		super();
		db = new Database("com.mysql.jdbc.Driver");
		db.open("jdbc:mysql://mysql.alwaysdata.com/gestionprojet_facebook","gestionprojet", "polytech");	
	} 
   
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			fbrclient = getAuthenticatedFacebookClient(request, response);
			long myID = fbrclient.users_getLoggedInUser();
			
			request.setAttribute("array", histoBaffes(myID));
			//response.setHeader("CACHE-CONTROL", "NO-CACHE");
			request.setAttribute("FB_APP_URL", FacebookServlet.FB_APP_URL);
			request.setAttribute("FB_API_KEY", FacebookServlet.FB_API_KEY);
			request.setAttribute("FB_APP_NAME", FacebookServlet.FB_APP_NAME);
			request.setAttribute("FB_SERVER_URL", FacebookServlet.FB_SERVER_URL);
			request.getRequestDispatcher("historique.jsp").forward(request, response);
		} catch (FacebookException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private ArrayList <String[]> histoBaffes(long uid){

		ArrayList <String []> array = new ArrayList <String[]>();
		String requete = "Select * From baffes Where idE = " + uid + " OR idR = " + uid;
		DataSet data = db.executeQuery(requete);
				
		for (int i = 0; data.hasMoreElements(); ++i){
			String res[] = data.nextElement();
			if (Integer.parseInt(res[2]) == uid){
				res[2] = "0";
				res[0] = res[3];
				res[3] = getName(Long.parseLong(res[3]));
			}
			else {
				res[3] = "0";
				res[0] = res[2];
				res[2] = getName(Long.parseLong(res[2]));
			}
			array.add(res);
		}
		return array;
		
		
	}
	private String getName(Long uid){
		try {
			Document d = fbrclient.fql_query("Select name from user Where uid="+uid);
			return d.getElementsByTagName("name").item(0).getTextContent();
		} catch (FacebookException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}